package com.cola.service;

import com.alibaba.fastjson.JSON;
import com.cola.dao.ShopDao;
import com.cola.entity.Customer;
import com.cola.entity.JoinSaleActivity;
import com.cola.entity.mep.Mep;
import com.cola.entity.order.Order;
import com.cola.entity.order.OrderDetail;
import com.cola.entity.shop.Goods;
import com.cola.entity.shop.SaleActivity;
import com.cola.entity.shop.ShopCar;
import com.cola.entity.shop.ShopCarGoods;
import com.cola.enums.OrderDetailType;
import com.cola.enums.OrderType;
import com.cola.enums.SaleType;
import com.cola.utils.DateUtils;
import com.cola.utils.PropertyUtils;
import com.cola.utils.SnowflakeIdWorker;
import com.cola.utils.baiduMap.BaiduMapUtils;
import com.cola.utils.baiduMap.entity.BaiduMapResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 店铺业务逻辑类
 * Created by Tony on 2017/8/22.
 */
public class ShopService {
    private final Logger logger =  LoggerFactory.getLogger(getClass());
    private static volatile ShopService instance = null;
    public static ShopService getInstance() {
        if (instance == null) {
            synchronized (ShopService.class) {
                if (instance == null) {
                    instance = new ShopService();
                }
            }
        }
        return instance;
    }

    /**
     * 新增店铺
     * @param customer_name
     * @param area
     * @param address
     * @param customer_mobile
     * @param customer_contact_name
     * @return
     */
    public boolean addShop(String customer_name , String city, String area, String address, String customer_mobile, String customer_contact_name, String main_image,String customer_img, String channel_type, String shop_size){
        BaiduMapResult baiduMapResult = BaiduMapUtils.getLocationInfoByAddress(address);
        BigDecimal lat = BigDecimal.valueOf(0);
        BigDecimal lng = BigDecimal.valueOf(0);
        if(baiduMapResult!=null){
            lat = baiduMapResult.getResult().getLocation().getLat();
            lng = baiduMapResult.getResult().getLocation().getLng();
        }
        return ShopDao.getInstance().addShop(customer_name, city, area, address, customer_mobile, customer_contact_name, main_image,customer_img, channel_type, shop_size,lat,lng);
    }

    /**
     * 编辑店铺信息
     * @param customer_id
     * @param customer_name
     * @param area
     * @param address
     * @param customer_mobile
     * @param customer_contact_name
     * @return
     */
    public boolean editShop(Integer customer_id, String customer_name ,String city, String area, String address, String customer_mobile, String customer_contact_name,String main_image, String customer_img, String shop_size){
        BaiduMapResult baiduMapResult = BaiduMapUtils.getLocationInfoByAddress(address);
        BigDecimal lat = BigDecimal.valueOf(0);
        BigDecimal lng = BigDecimal.valueOf(0);
        if(baiduMapResult!=null){
            lat = baiduMapResult.getResult().getLocation().getLat();
            lng = baiduMapResult.getResult().getLocation().getLng();
        }
        return ShopDao.getInstance().editShop(customer_id,customer_name,city,area,address,customer_mobile,customer_contact_name,main_image,customer_img,shop_size,lat,lng);
    }


    //==================================商品相关===================================================

    /**
     * 获取全部商品列表
     * @param areaNo,saleChannelNo ;销售区域编号 销售渠道编号
     * @return 
     * @author Max
     * @since 2017/9/14
     */
    public List<Goods> getGoodsList(String areaNo,String saleChannelNo){
        //获取商品列表
        List<Goods> goodsList = ShopDao.getInstance().getGoodsList(areaNo,saleChannelNo);
        //获取促销列表
        List<SaleActivity> saleList = ShopDao.getInstance().getSaleActivityList(areaNo,saleChannelNo);
        List<SaleActivity> tempSaleList = new ArrayList<SaleActivity>();
        for (Goods goods : goodsList){
            for (SaleActivity saleActivity : saleList){
                tempSaleList = new ArrayList<SaleActivity>();
                if(goods.getGoods_no().equals(saleActivity.getGoods_no())){
                    tempSaleList.add(saleActivity);
                }
                if(tempSaleList.size()>0){
                    goods.setSale_list(tempSaleList);
                }
            }
        }
        return goodsList;
    }


    //============================================================================================


    //====================================购物车===================================================

    /**
     * 获取购物车页面显示详情信息
     * @param customerId 店铺id
     * @param areaNo 区域编号
     * @param saleChannelNo 渠道编号
     * @return ShopCar
     * @author Max
     * @since 2017/9/16
     */
    public ShopCar getShopCarDetailInfo(Integer customerId,String areaNo,String saleChannelNo){
        List<ShopCarGoods> list = ShopDao.getInstance().getShopCarGoodsDetailList(customerId, areaNo, saleChannelNo);
        //获取促销列表
        List<SaleActivity> saleList = ShopDao.getInstance().getSaleActivityList(areaNo,saleChannelNo);
        List<SaleActivity> tempSaleList = new ArrayList<SaleActivity>();
        for (ShopCarGoods goods : list){
            for (SaleActivity saleActivity : saleList){
                tempSaleList = new ArrayList<SaleActivity>();
                if(goods.getGoods_no().equals(saleActivity.getGoods_no())){
                    tempSaleList.add(saleActivity);
                }
                if(tempSaleList.size()>0){
                    goods.setSale_activities(tempSaleList);
                }
            }
        }
        ShopCar shopCar = new ShopCar();
        BigDecimal price = new BigDecimal("0");
        for (ShopCarGoods shopCarGoods : list){
            price = price.add(shopCarGoods.getGoods_price().multiply(new BigDecimal(shopCarGoods.getGoods_num())));
        }
        shopCar.setGoods_list(list);
        shopCar.setPrice(price);

        return shopCar;
    }


    /**
     * 获取购物车页面显示详情信息
     * @param customerId 店铺id
     * @param areaNo 区域编号
     * @param saleChannelNo 渠道编号
     * @param goodsNoList 选择的商品列表编号
     * @return ShopCar
     * @author Max
     * @since 2017/9/16
     */
    public ShopCar getOrderGoodsDetailInfo(Integer customerId,String areaNo,String saleChannelNo,List<String> goodsNoList){
        List<ShopCarGoods> list = ShopDao.getInstance().getShopCarGoodsDetailList(customerId, areaNo, saleChannelNo);
        //获取促销列表
        List<SaleActivity> saleList = ShopDao.getInstance().getSaleActivityList(areaNo,saleChannelNo);
        List<SaleActivity> tempSaleList = new ArrayList<SaleActivity>();

        List<SaleActivity> realSaleList = new ArrayList<SaleActivity>();

        Integer status =0;
        for (ShopCarGoods goods : list){
            for (SaleActivity saleActivity : saleList){
                if(goodsNoList.contains(goods.getGoods_no())){
                    tempSaleList = new ArrayList<SaleActivity>();
                    if(goods.getGoods_no().equals(saleActivity.getGoods_no())){
                        tempSaleList.add(saleActivity);

                        for(SaleActivity realSaleActivity : realSaleList){
                            status=0;
                            if(realSaleActivity.getSale_no().equals(saleActivity.getSale_no())){
                                status=1;
                                realSaleActivity.setReal_num( realSaleActivity.getReal_num() + goods.getGoods_num());
                            }
                        }
                        if(status==0){
                            saleActivity.setReal_num(goods.getGoods_num());
                            realSaleList.add(saleActivity);
                        }
                    }
                    if(tempSaleList.size()>0){
                        goods.setSale_activities(tempSaleList);
                    }
                }
            }
        }
        return analysisSaleActivity(list,realSaleList);
    }

    /**
     * 处理促销活动
     * @param list 商品列表
     * @param realSaleList 实际促销活动列表
     * @return ShopCar
     * @author Max
     * @since 2017/9/16
     */
    private ShopCar analysisSaleActivity(List<ShopCarGoods> list,List<SaleActivity> realSaleList){
        try{
            ShopCar shopCar = new ShopCar();
            BigDecimal price = new BigDecimal("0");
            for (ShopCarGoods shopCarGoods : list){
                price = price.add(shopCarGoods.getGoods_price().multiply(new BigDecimal(shopCarGoods.getGoods_num())));
            }

            if(realSaleList.size()>0){

                SaleActivity joinSaleActivity = getAnSaleActivity(realSaleList);

                if(joinSaleActivity!=null){

                    shopCar.setSale_type(joinSaleActivity.getSale_type());

                    shopCar.setSale_no(joinSaleActivity.getSale_no());

                    if(joinSaleActivity.getSale_type().equals("PRICE_OFF")){

                        price = price.subtract(joinSaleActivity.getOff_price());
                        if(price.compareTo(new BigDecimal("0"))<0){
                            price = new BigDecimal("0");
                        }
                        shopCar.setOff_price(joinSaleActivity.getOff_price());

                    }else if(joinSaleActivity.getSale_type().equals("SEND_GIVEAWAY")){
                        ShopCarGoods goods = getGiveawayInfo(joinSaleActivity.getGiveaway_no());
                        goods.setGoods_price(new BigDecimal("0"));
                        goods.setGoods_num(joinSaleActivity.getGiveaway_num());
                        list.add(goods);
                    }
                }
            }
            shopCar.setGoods_list(list);

            shopCar.setPrice(price);

            return shopCar;
        }catch (Exception e){

            logger.error("处理促销活动时异常！",e);
        }
        return null;

    }


    
    /**
     * 获取一个符合条件的促销活动
     * @param realSaleActivity
     * @author Max
     * @since 2017/9/16
     */
    private SaleActivity getAnSaleActivity(List<SaleActivity> realSaleActivity){
        for (SaleActivity saleActivity : realSaleActivity){
            if(saleActivity.getBuy_num()<= saleActivity.getReal_num()){
                return saleActivity;
            }
        }
        return null;
    }


    /**
     * 获取赠品信息
     * @param giveaway_no
     * @return
     * @author Max
     * @since 2017/9/16
     */
    private ShopCarGoods getGiveawayInfo(String giveaway_no){
        return ShopDao.getInstance().getGiveawayInfo(giveaway_no);
    }


    /**
     * 获取购物车信息
     * @param customerId 店铺id
     * @param areaNo 区域编号
     * @param saleChannelNo 渠道编号
     * @return ShopCar
     * @author Max
     * @since 2017/9/15
     */
    public ShopCar getShopCarInfo(Integer customerId,String areaNo,String saleChannelNo){
        List<ShopCarGoods> list = ShopDao.getInstance().getShopCarGoodsList(customerId, areaNo, saleChannelNo);

        ShopCar shopCar = new ShopCar();

        BigDecimal price = new BigDecimal("0");
        for (ShopCarGoods shopCarGoods : list){
            price = price.add(shopCarGoods.getGoods_price().multiply(new BigDecimal(shopCarGoods.getGoods_num())));
        }
        shopCar.setGoods_list(list);
        shopCar.setPrice(price);
        return shopCar;
    }

    /**
     * 添加商品到购物车
     * @param customerId 店铺编号
     * @param goodsNo 商品编号
     * @param num 数量
     * @return true false
     * @author Max
     * @since 2017/9/15
     */
    public boolean addToShopCar(Integer customerId,String goodsNo,Integer num){
        return ShopDao.getInstance().addToShopCar(customerId,goodsNo,num);
    }

    /**
     * 购物车删除商品
     * @param customerId 店铺编号
     * @param goodsNo 商品编号
     * @param num 数量
     * @return
     * @author Max
     * @since 2017/9/15
     */
    public boolean subFromShopCar(Integer customerId,String goodsNo,Integer num){
        return ShopDao.getInstance().subFromShopCar(customerId,goodsNo,num);
    }

    /**
     * 清空购物车
     * @param customerId
     * @return false true
     * @author Max
     * @since 2017/9/18
     */
    public boolean emptyShopCar(Integer customerId){
        return ShopDao.getInstance().emptyShopCar(customerId);
    }

    //=============================================================================================

    //========================================订单=================================================


    /**
     * 根据店铺系统编号获取推荐经销商
     * @author Max
     * @since 2017/9/16
     */
    public List<Mep> getMepList(Customer customer){
       //354228749417451520
        try{

            List<Mep> rList = MepService.getInstance().getRecommendMepByCustomerNo(customer.getCustomer_system_no());

            if(rList!=null && rList.size()>0){
                return rList;
            }

            List<Mep> returnList = new ArrayList<Mep>();

            List<Mep> mepList = MepService.getInstance().getMepInfoByCityNo(customer.getCity());

            List<Mep> tempList = new ArrayList<Mep>();

            if(mepList!=null && mepList.size()>0){
                double tempDistance = 0.0;
                //推荐距离
                Double distance = Double.parseDouble(PropertyUtils.getProperty("distance"));
                for (Mep mep : mepList){
                    tempDistance = BaiduMapUtils.getDistanceByLngAndLat(customer.getCustomer_lat(),customer.getCustomer_lng(),mep.getMep_lat(),mep.getMep_lng());
                    if(tempDistance<distance){
                        mep.setDistance(tempDistance);
                        tempList.add(mep);
                    }
                }

                //将各个经销商的距离进行排序
                Collections.sort(tempList, new Comparator<Mep>() {
                    public int compare(Mep o1, Mep o2) {
                        return o1.getDistance().compareTo(o2.getDistance());
                    }
                });
                returnList.addAll(tempList);
            }
            return returnList;
        }catch (Exception e){
            logger.error("获取推荐经销商异常！",e);
        }
        return null;
    }


    /**
     * 创建订单
     * @param customer 店铺信息
     * @param shopCar 购物信息
     * @param mepNo 经销商编号
     * @return false true
     * @author Max
     * @since 2017/9/16
     */
    public boolean createOrder(Customer customer,ShopCar shopCar,String mepNo){
        Order order = new Order();
        String orderNo = getNewOrderNo();
        String check_code = customer.getCustomer_id()+getCheckCode();
        JoinSaleActivity saleActivity = new JoinSaleActivity();
        saleActivity.setOrder_no(orderNo);
        try{
            //组装Order
            order.setOrder_no(orderNo);//订单号

            order.setCustomer_id(customer.getCustomer_id());//店铺编号

            order.setMep_no(mepNo);//经销商编号

            order.setCity_no(customer.getCity());

            order.setCity_name(customer.getCity_name());

            order.setArea_no(customer.getArea());

            order.setArea_name(customer.getArea_name());

            order.setAddress(customer.getAddress());

            order.setOrder_price(shopCar.getPrice());

            order.setOrder_price_final(shopCar.getPrice());

            order.setGoods_num(shopCar.getGoods_list().size());

            order.setGoods_num_final(shopCar.getGoods_list().size());

            order.setMobile(customer.getCustomer_mobile());

            order.setReceiver(customer.getCustomer_name());

            order.setOrder_status(OrderType.WAITING_FOR_RECEIVING_ORDER.getValue());

            order.setCustomer_evaluate_status(0);

            order.setCheck_code(check_code);

            if(shopCar.getSale_type()!=null){
                if(shopCar.getSale_type().equals(SaleType.PRICE_OFF.getValue())){
                    order.setOff_price(shopCar.getOff_price());

                    order.setOff_price_final(shopCar.getOff_price());

                    order.setIs_price_off(1);
                }
                saleActivity.setSale_json(JSON.toJSONString(ShopDao.getInstance().getSaleActivityBySaleNo(shopCar.getSale_no())));
                saleActivity.setSale_type(shopCar.getSale_type());
                order.setSale_no(shopCar.getSale_no());
            }


            List<OrderDetail> details = new ArrayList<OrderDetail>();

            OrderDetail detail = new OrderDetail();
            for (ShopCarGoods shopCarGoods : shopCar.getGoods_list()){
                detail = new OrderDetail();
                if(shopCarGoods.getGoods_type().equals(OrderDetailType.GIVEAWAY.getValue())){
                    detail.setType(OrderDetailType.GIVEAWAY.getValue());
                }else{
                    detail.setType(OrderDetailType.MAIN.getValue());
                }

                detail.setOrder_no(orderNo);

                detail.setMep_no(mepNo);

                detail.setCustomer_id(customer.getCustomer_id());

                detail.setGoods_no(shopCarGoods.getGoods_no());

                detail.setGoods_name(shopCarGoods.getGoods_name());

                detail.setGoods_img(shopCarGoods.getGoods_img());

                detail.setGoods_num(shopCarGoods.getGoods_num());

                detail.setGoods_num_final(shopCarGoods.getGoods_num());

                detail.setGoods_unit_price(shopCarGoods.getGoods_price());

                detail.setGoods_price(shopCarGoods.getGoods_price().multiply(new BigDecimal(shopCarGoods.getGoods_num())));

                detail.setGoods_price_final(shopCarGoods.getGoods_price().multiply(new BigDecimal(shopCarGoods.getGoods_num())));

                detail.setStatus(1);

                detail.setGoods_specifications(shopCarGoods.getGoods_specifications());

                details.add(detail);
            }

            order.setOrder_details(details);
            String date = DateUtils.getCurrentDateTime();

            //添加消息
            boolean a = MessageService.getInstance().addOrderMessage(orderNo,mepNo,customer.getCustomer_name(),date);

            boolean b = ShopDao.getInstance().createOrder(order,customer.getCustomer_id(),date,saleActivity);

            return a && b;
        }catch (Exception e){

            return false;
        }
    }

    /**
     * 获取订单列表
     * @param customerId
     * @return List<Order>
     * @author Max
     * @since 2017/9/17
     */
    public List<Order> getAllOrderList(Integer customerId){

        List<Order> orderList = ShopDao.getInstance().getOrderList(customerId);

        List<OrderDetail> orderDetails = ShopDao.getInstance().getOrderDetailList(customerId);

        List<OrderDetail> tempList = new ArrayList<OrderDetail>();
        for(Order order : orderList){
            tempList = new ArrayList<OrderDetail>();
            for (int i = 0; i<orderDetails.size();i++){
                if(orderDetails.get(i).getOrder_no().equals(order.getOrder_no())){
                    tempList.add(orderDetails.get(i));
                    order.setOrder_details(tempList);
                }
            }
        }
        return orderList;
    }


    /**
     * 根据订单编号获取订单详情
     * @param orderNo 订单编号
     * @return Order
     * @author Max
     * @since 2017/9/17
     */
    public Order getOrderInfoByOrderNo(String orderNo){
        Order order = ShopDao.getInstance().getOrderInfoByOrderNo(orderNo);

        order.setOrder_details(ShopDao.getInstance().getOrderDetailInfoByOrderNo(orderNo));

        return order;
    }


    private String getNewOrderNo(){
        return "COLA"+System.currentTimeMillis();
    }

    /**
     * 获取一个唯一的check_code
     * @return check_code
     * @author Max
     * @since 2017/9/20
     */
    private String getCheckCode(){
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(3, 3);
        return String.valueOf(idWorker.nextId());
    }

    //=======================================个人中心=============================================

    /**
     * 保存修改信息
     * @param customer 店铺信息
     * @return true,false
     * @author Max
     * @since 2017/9/18
     */
    public boolean editShopInfo(Customer customer){
        return ShopDao.getInstance().editShopInfo(customer);
    }


    /**
     * 保存修改地址信息
     * @param customer 店铺信息
     * @return true,false
     * @author Max
     * @since 2017/9/18
     */
    public boolean editShopAddressInfo(Customer customer){
        return ShopDao.getInstance().editShopAddressInfo(customer);
    }

    /**
     * 保存店铺信息
     * @param customer
     * @return true;false
     * @author Max
     * @since 2017/9/20
     */
    public boolean saveShopInfo(Customer customer){
        return ShopDao.getInstance().saveShopInfo(customer);
    }


    /**
     * 配送评价
     * @param speed_score 速度评分
     * @param courier_score 配送评分
     * @param goods_score 商品完好度
     * @param evaluate_content 评价内容
     * @param orderNo 订单编号
     * @param mepNo 经销商编号
     * @param courierId 配送员Id
     * @return true false
     * @author Max
     * @since 2017/9/20
     */
    public boolean doEvaluate(Integer speed_score,Integer courier_score,Integer goods_score,String evaluate_content
            ,String orderNo,String mepNo,Integer courierId){
        return ShopDao.getInstance().doEvaluate(speed_score, courier_score, goods_score, evaluate_content, orderNo, mepNo, courierId);
    }

    //============================================================================================

    public static void main(String[] args){
//        getInstance().getPropretyMepInfo(9);
//        System.out.println(JSON.toJSONString(getInstance().getGoodsList("23","Q004")));
        System.out.println(JSON.toJSONString(getInstance().getMepList(null)));

    }
}
